package tech.hdis.framework.sms.aliyun;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import tech.hdis.framework.sms.SMS;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 阿里云短信发送实现
 *
 * @author 黄志文
 */
@Slf4j
@Component
public class AliyunSMSImpl implements SMS {

    private static final String RESPONSE_CODE_OK = "OK";

    @Resource
    private IAcsClient client;
    @Resource
    private AliyunSmsProperties aliyunSmsProperties;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信
     *
     * @param number       电话号码
     * @param templateCode 短信模板号
     * @param params       发送参数
     * @return 是否发送成功
     * @throws Exception 验证码异常
     */
    @Override
    public boolean sendSMS(@NonNull String number, @NonNull String templateCode, @NonNull Map<String, String> params) throws Exception {
        //组装短信发送器
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(number);
        request.setSignName(aliyunSmsProperties.getSignName());
        request.setTemplateCode(templateCode);
        request.setTemplateParam(JSON.toJSONString(params));
        //发送验证码
        SendSmsResponse sendSmsResponse = client.getAcsResponse(request);
        if (sendSmsResponse != null) {
            log.debug("短信发送结果状态码：{}", sendSmsResponse.getCode());
            log.debug("短信发送结果信息：{}", sendSmsResponse.getMessage());
        }
        return sendSmsResponse != null && sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals(RESPONSE_CODE_OK);
    }
}
